module WWW
  class Tkd
    class TbBuyerOrder < ActiveRecord::Base
      @@LOG_FLAG="TbBuyerOrder"
      #判断订单是否存在
      def self.find_from_order_id_and_user_id(order_id,user_id)
        return self.find_by_order_id_and_user_id(order_id,user_id)
      end
      #買家自动关联卖家设置的快递单信息
      def self.auto_relate_seller_express_id buyer_order,order
        tb_user = WWW::Tkd::TbUser.find_by_domain_login_id order.seller_nick
        if tb_user!=nil
          seller_order = WWW::Tkd::TbSellerOrder.find_by_order_id_and_user_id(order.id,tb_user.id)
          if seller_order!=nil
            ori_express_id = buyer_order.express_id
            if ori_express_id!=seller_order.express_id#只有快遞更新後才會更改
              buyer_order.is_newer = true
              buyer_order.express_id = seller_order.express_id
              buyer_order.save
              #記錄買家自動關聯到賣家設置的快遞信息
              WWW::Tkd::Logger.debug  "#{@@LOG_FLAG}buyer_auto_relate_seller_express","seller_id:#{seller_order.user_id},buyer_id:#{buyer_order.user_id},express_id:#{seller_order.express_id}"
            end
          end
        end
      end
      #订单与买家进行关联
      def self.relate_order_to_buyer order,session
        #将order与user关联到buyer_order表中
        buyer_order = self.find_by_user_id_and_order_id(session[:id],order.id)
        if buyer_order==nil
          buyer_order=self.new
          buyer_order.user_id=session[:id]
          buyer_order.order_id=order.id
          buyer_order.save
        end
        auto_relate_seller_express_id buyer_order,order
      end
      #将Taobao的数据导入到tb_order表中，并与tb_seller_order进行关联
      def self.save_from_tabao items,session
        if items['trade']!=nil
          items['trade'].each do|item|
            order = WWW::Tkd::TbOrder.find_by_tid item['tid'][0].strip().to_s
            if order==nil
              orders = WWW::Tkd::Gold::Utils::Misc.parse_trade item
              orders.each do|item|
                item.save
                relate_order_to_buyer item,session
              end
            else
              relate_order_to_buyer order,session
            end
          end
        end
      end
    end
  end
end
